<template>
  <div>
    <el-form :inline="true">
      <!--按返厂批次号查询-->
      <el-form-item>
        <el-input v-model="searchDto.batch" clearable placeholder="返厂批次号">
        </el-input>
      </el-form-item>
      <!--按返还工厂查询-->
      <el-form-item>
        <el-select v-model="searchDto.factoryId" clearable placeholder="请选择工厂">
          <el-option
            v-for="item in factoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!--按省份查询,当角色类型为总部账号时才显示-->
      <el-form-item>
        <el-select v-if="roleType === '1'" v-model="searchDto.provinceCode" clearable placeholder="请选择省份">
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchReturn()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="exportLoading" @click="pointOverviewExport()">数据导出</el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card" v-model="activeName" @tab-click="unOperateClick(activeName)">
      <el-tab-pane label="未结单" name="unOperate">
        <custom-table
          :data="overviewList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="pagination"
          :operationColumn="operationColumn">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="已结单" name="alreadyOperate">
        <custom-table
          :data="overviewList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :pagination="alreadyPagination"
          :operationColumn="operationColumn">
        </custom-table>
      </el-tab-pane>
    </el-tabs>


    <el-dialog title="工厂收机详情" :visible.sync="detailDialogVisible" :close-on-click-modal="false">
      <!-- 工厂收机详情列表 -->
      <custom-table
        :data="detailList"
        :columns="detailColumns"
        :tableLoadingFlag="detailTableLoadingFlag"
        :pagination="batchDetailPagination">
      </custom-table>
      <div slot="footer">
        <el-button type="primary" @click="onBtnCancel()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {parseTime} from '@/utils'
  import CustomTable from '../../../components/table/CustomTable.vue'
  import RepairList from '../../../components/table/RepairList.vue'
  import {
    getRoleType,
    getOfficeType,
    getOutsourceType,
    getOfficeId,
    getOutsourceId
  } from '@/utils/token'
  import {apiGetFactoryList, apiGetCity} from '@/api/dictionary'
  import {apiGetOverviewList, apiGetOverviewBatchList, apiPointOverviewWrite, apiGetPointOverviewListExport} from
      '@/api/repairs/point/overview'
  import {downloadExcel} from "../../../utils";

  export default {
    components: {
      CustomTable,
      RepairList
    },
    name: 'return',
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        pointId: '',
        pointType: '',
        status: 0
      }
      this.getReturnList(listQuery)
      this.selectedFactoryInit()
      this.selectedProvinceInit()
    },
    data () {
      return {
        pickOption: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        // 用户角色类型
        roleType: getRoleType(),
        // 办事处类型 0:省办事处，1:市办事处
        officeType: getOfficeType(),
        // 省外包商 1
        outSource: getOutsourceType(),
        tableLoadingFlag: false,
        detailTableLoadingFlag: false,
        detailDialogVisible: false,
        columns: [
          {label: '月份', name: 'backTime', align: 'center', formatter: this.formatTime},
          {label: '返厂批次号', name: 'batch', width: '160', align: 'center'},
          {label: '返厂日期', name: 'backTime', width: '160', align: 'center', formatter: this.formatDate},
          {label: '返还工厂', name: 'returnFactoryName', align: 'center'},
          {label: '省', name: 'provinceName', width: '80', align: 'center'},
          {label: '地市', name: 'cityName', align: 'center'},
          {label: '型号', name: 'statistic', align: 'center'},
          {label: '返厂数量', name: 'returnNum', align: 'center'},
          {label: '已接收', name: 'receivedNum', align: 'center'},
          {label: '已拒收', name: 'refusedNum', align: 'center'},
          {label: '已返还', name: 'returnedNum', align: 'center'},
          {label: '网点待收机', name: 'unReceiptednum', align: 'center'},
          {
            label: '接收日期',
            name: 'factoryReceiveTime',
            width: '160',
            align: 'center',
            formatter: this.formatReceiveTimestamp
          },
          {
            label: '返还日期',
            name: 'factoryReturnTime',
            width: '160',
            align: 'center',
            formatter: this.formatReturnTimestamp
          },
          {
            label: '在厂时间(天)',
            name: 'inFactoryTime',
            width: '120',
            align: 'center',
            formatter: this.formatInFactoryTime,
            renderHeader: this.renderHeader
          }
        ],
        // 操作栏
        operationColumn: {
          width: '100',
          operations: [
            {name: '返厂详情', callback: this.getBatchDetail},
            {name: '打印返厂清单', callback: this.printReturnOrder}
          ]
        },
        detailColumns: [
          {label: '品牌', name: 'brandName', align: 'center'},
          {label: '型号', name: 'modelName', align: 'center'},
          {label: 'YSTSN', name: 'ystsn', width: 180, align: 'center'},
          {label: '状态', name: 'status', align: 'center', formatter: this.formatStatus},
          {label: '操作人', name: 'receiverName', width: 180, align: 'center'},
          {label: '接收时间', name: 'receiveTime', width: 180, align: 'center'}
        ],
        // tab标识量,unOperate为未结单，alreadyOperate为已结单
        activeName: 'unOperate',
        // 工厂list
        factoryList: [],
        // 省份list
        provinceList: [],
        // 查询条件
        searchDto: {
          batch: '',
          factoryId: '',
          provinceCode: ''
        },
        overviewList: [],
        detailList: [],
        pagination: this.getData(this.getReturnList),
        alreadyPagination: this.getData(this.getReturnList),
        batchDetailPagination: this.getData(this.getBatchDetail),
        exportLoading: false
      }
    },
    methods: {
      // 工厂选择初始化
      selectedFactoryInit () {
        this.tableLoadingFlag = true
        apiGetFactoryList().then(response => {
          let factoryList = response.data
          let factory = []
          for (let i in factoryList) {
            factory.push({'name': factoryList[i].name, 'id': factoryList[i].id})
          }
          this.factoryList = factory
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 省份选择初始化
      selectedProvinceInit () {
        this.tableLoadingFlag = true
        apiGetCity().then(response => {
          let provinceList = response.data
          let province = []
          for (let i in provinceList) {
            province.push({'name': provinceList[i].name, 'code': provinceList[i].code})
          }
          this.provinceList = province
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // tab切换事件
      unOperateClick (activeName) {
        if (activeName === 'unOperate') {
          let listQuery = {
            status: 0,
            pageNumber: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
          }
          this.getReturnList(listQuery)
        } else if (activeName === 'alreadyOperate') {
          let listQuery = {
            status: 1,
            pageNumber: this.alreadyPagination.currentPage,
            pageSize: this.alreadyPagination.pageSize
          }
          this.getReturnList(listQuery)
        }
      },
      formatTime (row, column, cellValue) {
        return parseTime(cellValue, '{m}') + '月'
      },
      formatDate (row, column, cellValue) {
        return parseTime(cellValue, '{y}-{m}-{d}')
      },
      // 设备状态格式化
      formatStatus (row, column, cellValue) {
        if (cellValue === null) {
          return '未接收'
        }
        return cellValue
      },
      // 为在厂时间列添加说明
      renderHeader (h, {column, $index}) {
        return [
          column.label,
          h(
            'el-tooltip',
            {
              props: {
                content: '在厂时间 = 实时日期 - 办事处发货日期 - 7天物流时间',
                placement: 'top'
              }
            },
            [
              h('span', {
                class: {'el-icon-question': true}
              })
            ]
          )
        ]
      },
      // 格式化在厂时间(计算得到的在厂时间小于0的,看作为0)
      formatInFactoryTime (row, column, cellValue) {
        if (cellValue < 0) {
          return 0
        } else {
          return cellValue
        }
      },
      // 格式化接受日期时间戳
      formatReceiveTimestamp (row, column, cellValue) {
        if (cellValue === null) {
          return '工厂暂未接收'
        } else {
          return parseTime(cellValue, '{y}-{m}-{d} {hh}:{ii}:{ss}')
        }
      },
      // 格式化返还日期时间戳
      formatReturnTimestamp (row, column, cellValue) {
        if (cellValue === null) {
          return '工厂暂未返还'
        } else {
          return parseTime(cellValue, '{y}-{m}-{d} {hh}:{ii}:{ss}')
        }
      },
      // 条件查询
      searchReturn () {
        let listQuery = {}
        if (this.activeName === 'unOperate') {
          this.pagination.currentPage = 1
          this.pagination.pageSize = 10
          listQuery.pageSize = this.pagination.pageSize
          listQuery.pageNumber = this.pagination.currentPage
        } else if (this.activeName === 'alreadyOperate') {
          this.alreadyPagination.currentPage = 1
          this.alreadyPagination.pageSize = 10
          listQuery.pageSize = this.alreadyPagination.pageSize
          listQuery.pageNumber = this.alreadyPagination.currentPage
        }
        this.getReturnList(listQuery)
      },
      getReturnList (listQuery) {
        this.tableLoadingFlag = true
        if (!listQuery.pointType && getRoleType() !== '1') {
          listQuery.pointType = getRoleType() === '2' ? 0 : 1
        }
        if (!listQuery.pointId && getRoleType() !== '1') {
          listQuery.pointId = getRoleType() === '2' ? getOfficeId() : getOutsourceId()
        }
        if (listQuery.batch === undefined) {
          listQuery.batch = this.searchDto.batch
        }
        if (listQuery.factoryId === undefined) {
          listQuery.factoryId = this.searchDto.factoryId
        }
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.searchDto.provinceCode
        }
        if (this.activeName === 'unOperate') {
          listQuery.status = 0
        } else if (this.activeName === 'alreadyOperate') {
          listQuery.status = 1
        }
        apiGetOverviewList(listQuery).then(response => {
          if (this.activeName === 'unOperate') {
            this.pagination.totalRecords = response.totalRecords
          } else if (this.activeName === 'alreadyOperate') {
            this.alreadyPagination.totalRecords = response.totalRecords
          }
          this.overviewList = response.data
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      // 页面数据导出
      pointOverviewExport () {
        let listQuery = {
          pointId: '',
          pointType: '',
          batch: this.searchDto.batch,
          factoryId: this.searchDto.factoryId,
          provinceCode: this.searchDto.provinceCode
        }
        if (!listQuery.pointType && getRoleType() !== '1') {
          listQuery.pointType = getRoleType() === '2' ? 0 : 1
        }
        if (!listQuery.pointId && getRoleType() !== '1') {
          listQuery.pointId = getRoleType() === '2' ? getOfficeId() : getOutsourceId()
        }
        if (this.activeName === 'unOperate') {
          listQuery.status = 0
        } else if (this.activeName === 'alreadyOperate') {
          listQuery.status = 1
        }
        this.exportLoading = true
        apiGetPointOverviewListExport(listQuery).then(response => {
          downloadExcel(response.data, '自有售后网点批次一览信息导出表')
          this.exportLoading = false
        }).catch(() => {
          this.exportLoading = false
        })
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      getBatchDetail (row) {
        this.detailList = []
        if (row.batch) {
          this.batch = row.batch
        } else {
          row.batch = this.batch
        }
        let listQuery = {
          pageNumber: this.batchDetailPagination.currentPage,
          pageSize: this.batchDetailPagination.pageSize,
          batch: row.batch
        }
        this.detailTableLoadingFlag = true
        apiGetOverviewBatchList(listQuery).then(response => {
          this.detailList = response.data
          this.batchDetailPagination.totalRecords = response.totalRecords
          this.detailDialogVisible = true
          this.detailTableLoadingFlag = false
        }).catch(() => {
          this.detailTableLoadingFlag = false
        })
      },
      // 打印返厂清单
      printReturnOrder (row) {
        let paramsPost = {
          batch: row.batch,
          pointId: '',
          pointType: ''
        }
        if (getRoleType() !== '1') {
          paramsPost.pointType = getRoleType() === '2' ? 0 : 1
          paramsPost.pointId = getRoleType() === '2' ? getOfficeId() : getOutsourceId()
        }
        apiPointOverviewWrite(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后返厂清单')
        }).catch(() => {
        })
      },
      onBtnCancel () {
        this.detailDialogVisible = false
        this.detailTableLoadingFlag = false
        this.batchDetailPagination.currentPage = 1
        this.batchDetailPagination.pageSize = 10
      }
    }
  }
</script>
<style lang="scss" scoped>
  .toolbar-header {
    border-top: 1px solid #ddd;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    background: #eef1f6;
    height: 35px;
    .toolbar-btn {
      margin-left: 10px;
    }
  }
</style>
